import json
import time

import numpy as np
import pandas as pd
import requests

def stock_sector_fund_flow_rank(
    indicator: str = "10日", sector_type: str = "行业资金流"
) -> pd.DataFrame:
    """
    东方财富网-数据中心-资金流向-板块资金流-排名
    http://data.eastmoney.com/bkzj/hy.html
    :param indicator: choice of {"今日", "5日", "10日"}
    :type indicator: str
    :param sector_type: choice of {"行业资金流", "概念资金流", "地域资金流"}
    :type sector_type: str
    :return: 指定参数的资金流排名数据
    :rtype: pandas.DataFrame
    """
    sector_type_map = {"行业资金流": "2", "概念资金流": "3", "地域资金流": "1"}
    indicator_map = {
        "今日": [
            "f62",
            "1",
            "f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124",
        ],
        "5日": [
            "f164",
            "5",
            "f12,f14,f2,f109,f164,f165,f166,f167,f168,f169,f170,f171,f172,f173,f257,f258,f124",
        ],
        "10日": [
            "f174",
            "10",
            "f12,f14,f2,f160,f174,f175,f176,f177,f178,f179,f180,f181,f182,f183,f260,f261,f124",
        ],
    }
    url = "http://push2.eastmoney.com/api/qt/clist/get"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    }
    params = {
        "pn": "1",
        "pz": "5000",
        "po": "1",
        "np": "1",
        "ut": "b2884a393a59ad64002292a3e90d46a5",
        "fltt": "2",
        "invt": "2",
        "fid0": indicator_map[indicator][0],
        "fs": f"m:90 t:{sector_type_map[sector_type]}",
        "stat": indicator_map[indicator][1],
        "fields": indicator_map[indicator][2],
        "rt": "52975239",
        "cb": "jQuery18308357908311220152_1589256588824",
        "_": int(time.time() * 1000),
    }
    r = requests.get(url, params=params, headers=headers)
    text_data = r.text
    json_data = json.loads(text_data[text_data.find("{"): -2])
    temp_df = pd.DataFrame(json_data["data"]["diff"])
    if indicator == "今日":
        temp_df.columns = [
            "-",
            "今日涨跌幅",
            "编码",
            "名称",
            "主力净流入额",
            "超大单流入额",
            "超大单流入占比",
            "大单流入额",
            "大单流入占比",
            "中单流入额",
            "中单流入占比",
            "小单流入额",
            "小单流入占比",
            "-",
            "主力净流入占比",
            "主力流入最大股",
            "今日主力净流入最大股代码",
            "是否净流入",
        ]

        temp_df = temp_df[
            [
                "名称",
                "今日涨跌幅",
                "主力净流入额",
                "主力净流入占比",
                "超大单流入额",
                "超大单流入占比",
                "大单流入额",
                "大单流入占比",
                "中单流入额",
                "中单流入占比",
                "小单流入额",
                "小单流入占比",
                "主力流入最大股",
                "编码",
            ]
        ]
        temp_df.sort_values(["主力净流入额"], ascending=False, inplace=True)
        temp_df.reset_index(inplace=True)
        temp_df["index"] = range(1, len(temp_df) + 1)
        temp_df.rename({"index": "序号"}, axis=1, inplace=True)
    elif indicator == "5日":
        temp_df.columns = [
            "-",
            "编码",
            "名称",
            "5日涨跌幅",
            "_",
            "主力净流入额",
            "主力净流入占比",
            "超大单流入额",
            "超大单流入占比",
            "大单流入额",
            "大单流入占比",
            "中单流入额",
            "中单流入占比",
            "小单流入额",
            "小单流入占比",
            "主力流入最大股",
            "_",
            "_",
        ]

        temp_df = temp_df[
            [
                "名称",
                "5日涨跌幅",
                "主力净流入额",
                "主力净流入占比",
                "超大单流入额",
                "超大单流入占比",
                "大单流入额",
                "大单流入占比",
                "中单流入额",
                "中单流入占比",
                "小单流入额",
                "小单流入占比",
                "主力流入最大股",
                "编码",
            ]
        ]
        temp_df.sort_values(["主力净流入额"], ascending=False, inplace=True)
        temp_df.reset_index(inplace=True)
        temp_df["index"] = range(1, len(temp_df) + 1)
        temp_df.rename({"index": "序号"}, axis=1, inplace=True)
    elif indicator == "10日":
        temp_df.columns = [
            "-",
            "编码",
            "名称",
            "_",
            "10日涨跌幅",
            "主力净流入额",
            "主力净流入占比",
            "超大单流入额",
            "超大单流入占比",
            "大单流入额",
            "大单流入占比",
            "中单流入额",
            "中单流入占比",
            "小单流入额",
            "小单流入占比",
            "主力流入最大股",
            "_",
            "_",
        ]

        temp_df = temp_df[
            [
                "名称",
                "10日涨跌幅",
                "主力净流入额",
                "主力净流入占比",
                "超大单流入额",
                "超大单流入占比",
                "大单流入额",
                "大单流入占比",
                "中单流入额",
                "中单流入占比",
                "小单流入额",
                "小单流入占比",
                "主力流入最大股",
                "编码",
            ]
        ]
        temp_df.sort_values(["主力净流入额"], ascending=False, inplace=True)
        temp_df.reset_index(inplace=True)
        temp_df["index"] = range(1, len(temp_df) + 1)
        temp_df.rename({"index": "序号"}, axis=1, inplace=True)
    return temp_df

def stock_sector_fund_flow_his(code: str, sector_type: str = "板块") -> pd.DataFrame:
    """
    东方财富网-数据中心-资金流向-板块资金流-具体板块-历史资金流
    https://data.eastmoney.com/bkzj/{板块编码}.html
    :param code: 板块编码
    :type indicator: str
    :param sector_type: choice of {"板块", "个股"}
    :type sector_type: str
    :return: 具体板块的历史资金流数据
    :rtype: pandas.DataFrame
    """
    if sector_type == "板块":
        secid = "90.{}".format(code)
        cb = "jQuery1123029697035143443373_1644841189707"
    elif sector_type == "个股":
        if code[0] == '6':
            secid = "1.{}".format(code)
        else:
            secid = "0.{}".format(code)
        cb = "jQuery1123012609710562968046_1644976981217"
    else:
        return None

    url = "https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    }
    params = {
        "cb": cb,
        "lmt": "0",
        "klt": "101",
        "fields1": "f1,f2,f3,f7",
        "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65",
        "ut": "b2884a393a59ad64002292a3e90d46a5",
        "secid": secid,
        "_": int(time.time() * 1000),
    }
    r = requests.get(url, params=params, headers=headers)

    text_data = r.text
    json_data = json.loads(text_data[text_data.find("{"): -2])
    # print(json_data)

    temp_df = pd.DataFrame(json_data["data"]["klines"])

    cols = [
        "日期",
        "主力净流入额",
        "小单流入额",
        "中单流入额",
        "大单流入额",
        "超大单流入额",
        "主力净流入占比",
        "小单流入占比",
        "中单流入占比",
        "大单流入占比",
        "超大单流入占比",
        "点数",
        "涨跌幅",
        "-",
        "-",
    ]
    lst = []
    for index, row in temp_df.iterrows():
        tu = tuple(row[0].split(","))
        lst.append(tu)
    new_df = pd.DataFrame.from_records(lst, columns=cols)

    return new_df


def stock_market_fund_flow_1(market: str) -> pd.DataFrame:
    """
    东方财富网-数据中心-资金流向-大盘
    http://data.eastmoney.com/zjlx/dpzjlx.html
    :param market: choice of {"沪市", "深市", "创业板"}
    :type market: str
    :return: 近期大盘的资金流数据
    :rtype: pandas.DataFrame
    """
    if market == "沪市":
        secid = "1.000001"
    elif market == "深市":
        secid = "0.399001"
    elif market == "创业板":
        secid = "0.399006"
    else:
        return None

    url = "http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    }
    params = {
        "cb": "jQuery112306517305749415173_1645427084040",
        "lmt": "0",
        "klt": "101",
        "fields1": "f1,f2,f3,f7",
        "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65",
        "ut": "b2884a393a59ad64002292a3e90d46a5",
        "secid": secid,
        "_": int(time.time() * 1000),
    }
    r = requests.get(url, params=params, headers=headers)
    text_data = r.text
    json_data = json.loads(text_data[text_data.find("{") : -2])
    content_list = json_data["data"]["klines"]
    temp_df = pd.DataFrame([item.split(",") for item in content_list])
    temp_df.columns = [
        "日期",
        "主力净流入-净额",
        "小单净流入-净额",
        "中单净流入-净额",
        "大单净流入-净额",
        "超大单净流入-净额",
        "主力净流入-净占比",
        "小单净流入-净占比",
        "中单净流入-净占比",
        "大单净流入-净占比",
        "超大单净流入-净占比",
        "收盘价",
        "涨跌幅",
        "深证-收盘价",
        "深证-涨跌幅",
    ]
    temp_df = temp_df[
        [
            "日期",
            "收盘价",
            "涨跌幅",
            "主力净流入-净额",
            "主力净流入-净占比",
            "超大单净流入-净额",
            "超大单净流入-净占比",
            "大单净流入-净额",
            "大单净流入-净占比",
            "中单净流入-净额",
            "中单净流入-净占比",
            "小单净流入-净额",
            "小单净流入-净占比",
        ]
    ]
    temp_df = temp_df.iloc[::-1]
    return temp_df

def stock_market_fund_real_time() -> pd.DataFrame:
    """
    取大盘的实时资金流
    """
    url = "https://push2.eastmoney.com/api/qt/ulist.np/get"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    }
    params = {
        "cb": "jQuery112305988024135032248_1650197979796",
        "fltt": "2",
        "secids": "1.000001,0.399001,0.399006",
        "fields": "f62,f66,f72,f78,f84",
        "ut": "b2884a393a59ad64002292a3e90d46a5",
        "_": int(time.time() * 1000),
    }
    r = requests.get(url, params=params, headers=headers)

    text_data = r.text
    json_data = json.loads(text_data[text_data.find("{"): -2])
    # print(json_data)

    temp_df = pd.DataFrame(json_data["data"]["diff"])
    field1 = temp_df["f62"][0] + temp_df["f62"][1]
    field2 = temp_df["f66"][0] + temp_df["f66"][1]
    field3 = temp_df["f72"][0] + temp_df["f72"][1]
    field4 = temp_df["f78"][0] + temp_df["f78"][1]
    field5 = temp_df["f84"][0] + temp_df["f84"][1]
    temp_df = pd.DataFrame(
        np.insert(temp_df.values, 0, values=[field1, field2, field3, field4, field5], axis=0))

    temp_df["市场"] = ["沪深两市", "沪市", "深市", "创业板"]

    temp_df.columns = [
        "主力净流入",
        "超大单净流入",
        "大单净流入",
        "中单净流入",
        "小单净流入",
        "市场",
    ]

    temp_df = temp_df[
        [
            "市场",
            "主力净流入",
            "超大单净流入",
            "大单净流入",
            "中单净流入",
            "小单净流入",
        ]
    ]
    return temp_df


